/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/
#pragma once

#include "kbase.h"
#include "kstream.h"
#include "kstructdata.h"
#include "kencoding.h"

class kTextReader : public kBase {
private:
	kStream* _stream;
	bool _swapEndian;

public:
	kTextReader(kStream* stream);
	~kTextReader();
	inline size_t read(tchar& c) {
		size_t s = _stream->read(kData((uint8_t*)&c, sizeof(c)));
		if (_swapEndian) {
			kDefaultEncoding<>::swapEndian(c);
		}
		return s;
	}
	inline size_t read(std::tstring& str, size_t length) {
		kStructDataBuffer buffer(sizeof(tchar), length);
		size_t s = _stream->read(buffer.getStructData());
		if (_swapEndian) {
			for (size_t i = 0; i < length; i++)
				kDefaultEncoding<>::swapEndian(buffer.item<tchar>(i));
		}
		str.assign(&buffer.item<tchar>(0), buffer.getItemCount());
		return s;
	}
	inline size_t readLn(std::tstring& str) {
		str = _T("");
		tchar c;
		size_t olds = 0;
		size_t s = read(c);
		while ((c != _T('\n')) && (s > olds)) {
			str += c;
			olds = s;
			s += read(c);
		}
		return s;
	}
};
